package com.ruoyi.blog.service.impl;


import com.ruoyi.blog.domain.TCategory;
import com.ruoyi.blog.mapper.TCategoryMapper;
import com.ruoyi.blog.service.ITCategoryService;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 类型Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-11-14
 */
@Service
public class TCategoryServiceImpl implements ITCategoryService
{
    @Autowired
    private TCategoryMapper tCategoryMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 查询类型
     * 
     * @param categoryId 类型主键
     * @return 类型
     */
    @Override
    public TCategory selectTCategoryByCategoryId(Long categoryId)
    {
        return tCategoryMapper.selectTCategoryByCategoryId(categoryId);
    }

    /**
     * 查询类型列表
     * 
     * @param tCategory 类型
     * @return 类型
     */
    @Override
    public List<TCategory> selectTCategoryList(TCategory tCategory)
    {
        return tCategoryMapper.selectTCategoryList(tCategory);
    }

    /**
     * 新增类型
     * 
     * @param tCategory 类型
     * @return 结果
     */
    @Override
    public int insertTCategory(TCategory tCategory)
    {
        tCategory.setCreateTime(DateUtils.getNowDate());
        if(tCategory.getParentId() == null){
            tCategory.setAncestors("0");
            tCategory.setParentId(0L);
        }else{
            TCategory info = tCategoryMapper.selectTCategoryByCategoryId(tCategory.getParentId());
            if(!UserConstants.DEPT_NORMAL.equals(info.getStatus())){
                throw new ServiceException("部门停用，不允许新增");
            }
            tCategory.setAncestors(info.getAncestors() + "," + info.getCategoryId());
        }
        int res = tCategoryMapper.insertTCategory(tCategory);
        deleteRedisKey(res);
        return res;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param categorys 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TCategory> buildCategoryTreeSelect(List<TCategory> categorys) {
        List<TCategory> returnList = new ArrayList<TCategory>();
        List<Long> tempList = new ArrayList<Long>();
        for (TCategory category : categorys)
        {
            tempList.add(category.getCategoryId());
        }
        for (Iterator<TCategory> iterator = categorys.iterator(); iterator.hasNext();)
        {
            TCategory category = (TCategory) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(category.getCategoryId()))
            {
                recursionFn(categorys, category);
                returnList.add(category);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = categorys;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<TCategory> list, TCategory t)
    {
        // 得到子节点列表
        List<TCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<TCategory> list, TCategory t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 得到子节点列表
     */
    private List<TCategory> getChildList(List<TCategory> list, TCategory t)
    {
        List<TCategory> tlist = new ArrayList<TCategory>();
        Iterator<TCategory> it = list.iterator();
        while (it.hasNext())
        {
            TCategory n = (TCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getCategoryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 根据ID查询所有子类型（正常状态）
     *
     * @param categoryId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenCategoryById(Long categoryId) {
        return tCategoryMapper.selectNormalChildrenCategoryById(categoryId);
    }

    /**
     * 是否存在部门子节点
     *
     * @param categoryId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByCategoryId(Long categoryId) {
        int result = tCategoryMapper.hasChildByCategoryId(categoryId);
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param tCategory 部门信息
     * @return 结果
     */
    @Override
    public String checkCategoryNameUnique(TCategory tCategory) {
        Long categoryId = StringUtils.isNull(tCategory.getCategoryId()) ? -1L : tCategory.getCategoryId();
        TCategory info = tCategoryMapper.checkCategoryNameUnique(tCategory.getText(), tCategory.getParentId());
        if (StringUtils.isNotNull(info) && info.getCategoryId().longValue() != categoryId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改类型
     * 
     * @param tCategory 类型
     * @return 结果
     */
    @Override
    public int updateTCategory(TCategory tCategory)
    {
        tCategory.setUpdateTime(DateUtils.getNowDate());
        TCategory newParentCategory = tCategoryMapper.selectTCategoryByCategoryId(tCategory.getParentId());
        TCategory oldCategory = tCategoryMapper.selectTCategoryByCategoryId(tCategory.getCategoryId());
        if (StringUtils.isNotNull(newParentCategory) && StringUtils.isNotNull(oldCategory))
        {
            String newAncestors = newParentCategory.getAncestors() + "," + newParentCategory.getCategoryId();
            String oldAncestors = oldCategory.getAncestors();
            tCategory.setAncestors(newAncestors);

            updateCategoryChildren(tCategory.getCategoryId(), newAncestors, oldAncestors);
        }
        int result = tCategoryMapper.updateTCategory(tCategory);
        deleteRedisKey(result);
        return result;
    }

    /**
     * 修改子元素关系
     *
     * @param categoryId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateCategoryChildren(Long categoryId, String newAncestors, String oldAncestors)
    {
        List<TCategory> children = tCategoryMapper.selectChildrenCategoryById(categoryId);
        for (TCategory child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            tCategoryMapper.updateCategoryChildren(children);
        }
    }

    /**
     * 批量删除类型
     * 
     * @param categoryIds 需要删除的类型主键
     * @return 结果
     */
    @Override
    public int deleteTCategoryByCategoryIds(Long[] categoryIds)
    {
        int res = tCategoryMapper.deleteTCategoryByCategoryIds(categoryIds);
        deleteRedisKey(res);
        return res;
    }

    /**
     * 删除类型信息
     * 
     * @param categoryId 类型主键
     * @return 结果
     */
    @Override
    public int deleteTCategoryByCategoryId(Long categoryId)
    {
        int res = tCategoryMapper.deleteTCategoryByCategoryId(categoryId);
        deleteRedisKey(res);
        return res;
    }

    @Override
    public boolean checkCategoryExistBlog(Long categoryId) {
        return false;
    }

    private void deleteRedisKey(int res){
        if(res > 0){
            if(redisService.hasKey("blogCategory")) redisService.deleteObject("blogCategory");
        }
    }
}
